/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action;

import controller.Action;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Exame;
import model.Funcionario;
import model.Paciente;
import persistence.ExameDAO;
import persistence.FuncionarioDAO;
import persistence.PacienteDAO;
import util.Validador;


/**
 *
 * @author aurelio.costa
 */
public class GravarExameAction implements Action{

    @Override
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String nomePaciente = request.getParameter("textNomePaciente");
        String idFuncionario = request.getParameter("funcionario");
        String dtExame = request.getParameter("textDtExame");
        String descricao = request.getParameter("textDecricao");
        
        if(!Validador.validaString(dtExame, idFuncionario, nomePaciente, descricao)){            
            response.sendRedirect("index.jsp");
        }else {
            try {
                FuncionarioDAO fDao = FuncionarioDAO.getInstace();
                Funcionario f = fDao.buscaFuncionarioPorNome(Integer.parseInt(idFuncionario));
                PacienteDAO pDao = PacienteDAO.getInstace();
                Paciente p = pDao.buscaPacientePorNome(nomePaciente);
                
                Exame exame = new Exame();
                exame.setPaciente(p);
                exame.setFuncionario(f);
                exame.setDtExame(new Date(dtExame));
                ExameDAO.getInstace().save(exame);               
                response.sendRedirect("sucesso.jsp");
                
            } catch (SQLException e) {
                response.sendRedirect("erro.jsp");
                e.printStackTrace();
            
            } catch (ClassNotFoundException e) {
                response.sendRedirect("contatoErro.jsp");
                e.printStackTrace();
            }
        }
    }
    
}
